package com.zx._03_并发.chapter_06_compent;

import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

/**
 * 同步组件——synchronized的死锁
 */
@Slf4j
public class Demo_08_synchronized的死锁 {

    public static void main(String[] args) {
        Object lockA = new Object();
        Object lockB = new Object();

        new Thread(() -> {
            synchronized (lockA) {
                System.out.println("A lockA begin");
                sleep();
                System.out.println("A lockB begin");
                synchronized (lockB) {
                    System.out.println("AAAAA");
                }
                System.out.println("A lockB end");
                System.out.println("A lockA end");
            }
        }).start();

        new Thread(() -> {
            synchronized (lockB) {
                System.out.println("B lockB begin");
                sleep();
                System.out.println("B lockA begin");
                synchronized (lockA) {
                    System.out.println("BBBBB");
                }
                System.out.println("B lockA end");
                System.out.println("B lockB end");
            }
        }).start();

    }

    public static void sleep() {
        try {
            TimeUnit.MILLISECONDS.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
